<?php

namespace app\common\services;

/**
 * 验证码服务
 * Class CodeService
 * @package app\common\services
 */
class CodeService extends BaseService{

    /**
     * 发送短信验证码
     * @param $mobile
     * @return bool
     * @throws \yii\web\HttpException
     */
    public static function sendMobileCode($mobile){
        if(\Yii::$app->getCache()->exists($mobile)){
            self::setError(\Yii::t("app","发送频率过快,请稍后再试"));
            return false;
        }

        $expire = \Yii::$app->params['code_expire'];
        if(YII_DEBUG){
            $code = "1234";
        }else{
            $code = random_int(1000,9999);
            if(!SmsService::send($mobile,\Yii::$app->params['sms_template']['mobile_login'],['#code','#expire'],[$code,$expire])){
                self::setError(SmsService::getError());
                return false;
            }
        }

        \Yii::$app->getCache()->set($mobile,$code,$expire * 60);
        return true;
    }

    /**
     * 校验验证码
     * @param $mobile
     * @param $code
     * @return bool
     * @throws \yii\base\InvalidConfigException
     */
    public static function verifyCode($mobile,$code){
        if(!\Yii::$app->getCache()->exists($mobile)){
            return false;
        }
        if(\Yii::$app->getCache()->get($mobile) != $code){
            return false;
        }
        \Yii::$app->getCache()->delete($mobile);
        return true;
    }
}